import * as cloudDb from '@agconnect/database-server';
import { user_topic } from './model/user_topic';
import * as agc from '@agconnect/common-server';
import * as Utils from './utils/Utils.js';

const ZONE_NAME = "HarmonyOSDeveloper";

export class DatabaseHelper {
  logger;
  cloudDbZone;

  constructor(context, logger) {
    this.logger = logger;
    const credential = Utils.getCredential(context, logger);
    try {
      // 初始化AGCClient
      logger.info("begin to init agcClient");
      let agcClient;
      try {
        agcClient = agc.AGCClient.getInstance();
      } catch {
        agc.AGCClient.initialize(credential);
        agcClient = agc.AGCClient.getInstance();
      }
      // 初始化AGConnectCloudDB实例
      logger.info("begin to init cloudDb");
      let cloudDbInstance;
      try {
        cloudDbInstance = cloudDb.AGConnectCloudDB.getInstance(agcClient);
      } catch {
        cloudDb.AGConnectCloudDB.initialize(agcClient);
        cloudDbInstance = cloudDb.AGConnectCloudDB.getInstance(agcClient);
      }
      // 创建CloudDBZoneConfig配置对象，并设置云侧CloudDB zone名称，打开Cloud DB zone实例
      const cloudDBZoneConfig = new cloudDb.CloudDBZoneConfig(ZONE_NAME);
      this.cloudDbZone = cloudDbInstance.openCloudDBZone(cloudDBZoneConfig);
    } catch (err) {
      logger.error("init CloudDBZoneWrapper error: " + err);
    }
  }

  async modifyTopic(followIds, userid) {
    let ids = followIds.split(',')
    if (!this.cloudDbZone) {
      console.log("CloudDBClient is null, try re-initialize it");
      return;
    }
    try {
      // 查询用户关注的所有主题
      if (userid) {
        const userTopicQuery = cloudDb.CloudDBZoneQuery.where(user_topic).equalTo("user_id", userid);
        const userTopicResp = await this.cloudDbZone.executeQuery(userTopicQuery);
        let userTopics = userTopicResp.getSnapshotObjects();
        this.logger.info("query userTopic success ");
        console.log('userTopicResp=>', userTopicResp.getSnapshotObjects());
        if (userTopics.length > 0) {
          // 删除所有之前关注的
          const deleteResp = await this.cloudDbZone.executeDelete(userTopics);
        }
        // 新增请求的
        let res = await this.insertTopic(ids, userid)
        return res;
      }


      return 0;
    } catch (error) {
      this.logger.info("insert topic error " + error);
      return undefined
    }
  }

  async insertTopic(followIds, userid) {
    if (!this.cloudDbZone) {
      console.log("CloudDBClient is null, try re-initialize it");
      return;
    }
    try {
      let topicList = [];
      for (let i = 0; i < followIds.length; i++) {
        let userTopic = new user_topic();
        userTopic.setId(followIds[i] + '' + userid);
        userTopic.setUser_id(userid);
        userTopic.setTopic_id(followIds[i]);
        topicList.push(userTopic);
      }
      const resp = await this.cloudDbZone.executeUpsert(topicList);
      this.logger.info("insert topic success ");
      console.log('resp=>', resp);
      return resp;
    } catch (error) {
      this.logger.info("insert topic error " + error);
      return undefined
    }
  }

  async deleteTopic(unfollowIds, userid) {
    if (!this.cloudDbZone) {
      console.log("CloudDBClient is null, try re-initialize it");
      return;
    }
    try {
      const cloudDBZoneQuery = cloudDb.CloudDBZoneQuery.where(user_topic);
      cloudDBZoneQuery.in("topic_id", unfollowIds)
      cloudDBZoneQuery.equalTo("user_id", userid)
      const resp1 = await this.cloudDbZone.executeQuery(cloudDBZoneQuery);
      console.log('resp1=>', resp1);
      let listData = resp1.getSnapshotObjects();
      const resp2 = await this.cloudDbZone.executeDelete(listData);
      this.logger.info("delete topic success ");
      console.log('resp=>', resp2);
      return resp2;
    } catch (error) {
      this.logger.info("delete topic error " + error);
      return undefined
    }
  }
}